package gupao.concurrency.concurrent.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class CyclicBarrierSample {
    static Random r = new Random();
    public static void main(String[] args) {

        CyclicBarrier cb = new CyclicBarrier(3);
        log.info("初始化：有 {} 个人正在赶来餐厅", (3 - cb.getNumberWaiting()));
        for (int i = 0; i < 3; i++) {
            //设置用户的编号
            final int person = i;
            new Thread(() -> {
                try {
                    //此处睡眠，模拟3个人从家里来到餐厅所花费的时间
                    Utils.sleepIgnoreExp(r.nextInt(5000) + 1000);
                    log.info("用户 {} 到达餐厅了, 当前已有 {} 个人到达餐厅", person, (cb.getNumberWaiting() + 1));
                    cb.await();
                    //三个人都到到餐厅啦，开始吃饭
                    eat(person);
                    //再次wait(),等待3个人全部吃完饭 ，然后去打游戏
                    cb.await();
                    //3个人都到达网吧了，开始玩游戏 playGame()...
                    log.info("全部吃好饭，可以打游戏去咯..");
                } catch (InterruptedException | BrokenBarrierException e) {
                }
            }).start();
        }
    }

    static void eat(int person){
        log.info("{} 开始吃饭...", person);
        Utils.sleepIgnoreExp(r.nextInt(5000) + 1000);
        log.info("{}  吃完饭", person);
    }

}
